<?php
/**
 * SmartyRenderer class definition
 *   
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MVP-PHP
 */
require_once 'interfaces/iViewRenderer.php';
require_once 'lib/Smarty/Smarty.class.php';
require_once 'lib/HTML_QuickForm/QuickForm/Renderer/ArraySmarty.php';

/**
 * Renders Views using Smarty
 * @package MVP-PHP
 * @subpackage Renderers
 */   
class SmartyRenderer extends ViewRenderer implements iViewRenderer
{
	/**
     * Smarty templates have the extension .tpl
	 */ 	
	const TEMPLATE_EXT = '.tpl';
	
	/**
     * Constructor
	 */ 	
	public function __construct()
	{
		parent::__construct();
		
		$this->smarty = new Smarty;
		$this->smarty->template_dir = ROOT_DIR;
		$this->smarty->compile_dir = LIB_DIR .'/Smarty/templates_c';
		$this->smarty->cache_dir = LIB_DIR .'/Smarty/cache';
		$this->smarty->config_dir = LIB_DIR .'/Smarty/configs';
	}
	
	/**
     * Renders the Views
	 */ 	
	public function Render()
	{
		$this->CoalesceViews();
		$this->LoadPropertiesIntoSmarty();
		
		if (empty($this->templateFile) && !($this->SetTemplateFile(TEMPLATE_PREFIX . self::TEMPLATE_EXT))) {
			throw new Exception("SmartyRenderer templateFile is empty");
		}
		
		$this->smarty->display($this->templateFile);
	}
	
	/**
     * Assigns all view properties into Smarty and renders any HTML_QuickForms
	 */  	
	protected function LoadPropertiesIntoSmarty()
	{
		if (count($this->properties) > 0) {
			foreach ($this->properties as $key => $value) {
				$this->smarty->assign($key, $value);
			}
		}
		
		if (count($this->views) > 0) {
			foreach ($this->views as $view) {
				if ($view instanceof HTMLQuickFormView) {	
					$renderer = new HTML_QuickForm_Renderer_ArraySmarty($this->smarty);				
					$view->form->accept($renderer);	
					$this->smarty->assign($view->formName, $renderer->toArray());							
				} 
			}
		}
	}
	
	/**
     * Smarty instance
     * @var Smarty 
	 */ 	
	protected $smarty;
}

?>
